/*
 * @Autor: 陈锦
 * @Date: 2021-05-25 08:46:05
 * @LastEditors: 陈锦chenjin
 * @LastEditTime: 2022-01-10 15:05:09
 * @Description: 红星闪闪
 */
// 引入插件
import request from './request.js';
import { baseUrl } from './config.js';


// import Vue from 'vue';
import store from '@/store/index';

// export const baseUrl = store.state.baseUrl;

// Vue.prototype.$baseUrl = baseUrl
// Vue.prototype.$imageBaseUrl = imageBaseUrl
// 全局配置
request.setConfig({
	baseUrl: baseUrl,
	// dataType: 'json', // 可删除，默认为json
	// responseType: 'application/json;charset=UTF-8;', // 可删除，默认为text
	// 设置请求头，支持所有请求头设置，也可不设置，去掉header就行
	header: {
		'content-type': 'application/json;charset=UTF-8',
		Authorization: 'Bearer ' + uni.getStorageSync('token') ,
	},
	timeout: 3000,
	sslVerify: false, 
});
console.log(uni.getStorageSync('token'),'token11111-----------------------------------------------------')
var num = 0;
let bearImei = true; //本地手机的imei和接口返回的最后登陆设备的imei进行对比不同时候，让拦截器返回，不发请求，避免多个模态框弹出
// 设置请求拦截器
request.interceptors.request(config => {
	// 配置参数和全局配置相同，此优先级最高，会覆盖在其他地方的相同配置参数
	// 追加请求头，推荐
	// config.header['content-type'] = 'application/json';
	// config.header.token = 'token from interceptors';

	// 覆盖请求头
	// config.header = {
	// 'content-type': 'application/json',
	// 'token': 'token from interceptors'
	// }

	// return false; // 终止请求
	// return Promise.reject('error from request interceptors'); // 向外层抛出错误，用catch捕获
	// uni.showLoading({
	//   title: '加载中',
	// mask: true
	// })
	// console.log('config',config)
	return config; // 返回修改后的配置，如未修改也需添加这行
});

// import usersM from './vuex/modules/users/mutations'
// 设置响应拦截器
request.interceptors.response(async res => {
	if (res.url == '/api/Login/getcheckcode') {
		bearImei = true;
		num = 1;
	}
	if (!bearImei) {
		return false; // 阻止返回,页面不会接收返回值
	} else {
		//除验证码和登陆外 禁止同一账号在多台终端登陆
		// if (res.url != '/api/Login/logincheck' && res.url != '/api/Login/getcheckcode') {
		//     getLastLoginInfo();
		// }
		if (store.state.token != '') {
			getLastLoginInfo();
		}
	}

	// 接收请求，执行响应操作
	// 您的逻辑......
	// uni.hideLoading()

	// return {message: '自定义值，来自拦截器'};   // 返回您自定义的值，将覆盖原始返回值
	// return Promise.reject('error from response interceptors') // 向外层抛出错误，用catch捕获
	// console.log('res.data',res)
	if(res.data.Code == 401){
		uni.reLaunch({
			url: '/pages/H5Login/login'
		});
		// uni.removeStorageSync('token'); //清除本地token                
		// uni.removeStorageSync('userName'); 
		// uni.removeStorageSync('phoneNumber'); 
	}
	if (res.statusCode) {
		if (res.statusCode == 200) {
			if (res.data.code == 401) {
				uni.showToast({
					title: 'token过期请重新登录',
					icon: 'none',
					duration: 5000,
				});
				uni.reLaunch({
					url: '/pages/H5Login/login',
					success: () => {
						store.commit('changeToken', ''); //清空vueX的token
					},
				});
			}
			return res.data;
		} else {
			uni.showToast({
				title: 'statusCode:' + res.statusCode + res.errMsg,
				icon: 'none',
				duration: 5000,
			});
			if (store.state.token != '') {
				writeErrorLog(res);
			}
		}
	} else {
		uni.showToast({
			title: res.errMsg + '服务器未知错误！',
			icon: 'none',
			duration: 5000,
		});

		if (store.state.token != '') {
			writeErrorLog(res);
		}
	}
});

export default request;
//调用错误日志接口
function writeErrorLog(res) {
	let url = baseUrl + '/api/Sys/WriteErrorLog';
	uni.request({
		url,
		method: 'POST',
		timeout: 5000,
		sslVerify: false,
		header: {
			'content-type': 'application/json',
			Authorization: 'Bearer ' + store.state.token,
			// Authorization: "Bearer " + uni.getStorageSync("token"),
		},
		data: {
			method: res.url,
			// parms: res.config.toString(),
			parms: JSON.stringify(res.config.data),
			errorMsg: res.errMsg,
		},
		success: response_err => {
			if (response_err.data.code == 200) {
				console.log('发生错误记录成功');
			}
		},
	});
}
//调用获取最后一次登陆信息的接口
function getLastLoginInfo() {
	// console.log( store.state.token);
	let params = {
		uid: store.state.UserInfo.uid,
	};
	// //获取最后一次的登陆信息
	uni.request({
		url: baseUrl + '/api/Login/getLastLoginInfo', //仅为示例，并非真实接口地址。
		method: 'POST',
		data: params,
		header: {
			'content-type': 'application/json',
			// Authorization: 'Bearer ' + store.state.token,
			Authorization: "Bearer " + uni.getStorageSync("token"),
		},
		timeout: 5000,
		sslVerify: false,
		success: res2 => {
			let resimei = res2.data.data;
			// #ifdef APP-PLUS
			// 获取设备信息
			plus.device.getInfo({
				success: e => {
					console.log(e)
					let currentimei = e.uuid;
					if (resimei && currentimei) {
						if (resimei != currentimei) {
							bearImei = false;
							handleImei();
						} else {
							bearImei = true;
						}
					}

				},
				fail: function(e) {
					console.log(e)
					uni.showToast({
						title: '设备信息读取失败',
						icon: 'none',
						duration: 2000,
					});
				},
			});
			//  #endif
		},
		fail: function(e) {
			uni.showToast({
				title: '/api/Login/getLastLoginInfo接口请求失败',
				icon: 'none',
				duration: 3000,
			});
		},
	});
}

function handleImei() {
	if (num == 1) {
		num++;
		uni.showModal({
			title: '该账号已在其他设备上登陆！当前账号已下线',
			content: '',
			cancelText: '退出应用',
			confirmText: '重新登陆',
			showCancel: true,
			success: res => {
				if (res.confirm) {
					uni.reLaunch({
						url: '/pagesJK/overviewPage/index',
						success: () => {
							bearImei = false;
							uni.removeStorageSync('token'); //清除本地token
							store.commit('changeToken', ''); //清空vueX的token
						},
					});
				} else if (res.cancel) {
					bearImei = false;

					uni.reLaunch({
						url: '/pagesJK/overviewPage/index',
						success: () => {
							store.commit('changeToken', ''); //清空vueX的token
						},
					});
					// #ifdef APP-PLUS
					plus.runtime.quit(); //退出应用
					//  #endif
				}
			},
		});
	}
}
